package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.OrderNumberGenerator;
import com.ruoyi.system.domain.dto.XsOrderQnImportDto;
import com.ruoyi.system.domain.xs.XsOrderQn;
import com.ruoyi.system.mapper.XsOrderQnMapper;
import com.ruoyi.system.service.IXsOrderQnService;
import com.ruoyi.system.service.IXsStoreService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 千牛订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-27
 */
@Service
public class XsOrderQnServiceImpl extends ServiceImpl<XsOrderQnMapper, XsOrderQn>
        implements IXsOrderQnService
{
    @Autowired
    private XsOrderQnMapper xsOrderQnMapper;

    @Autowired
    private IXsStoreService xsStoreService;

    private ThreadPoolTaskExecutor taskExecutor = SpringUtils.getBean("threadPoolTaskExecutor");

    /**
     * 查询千牛订单
     * 
     * @param id 千牛订单主键
     * @return 千牛订单
     */
    @Override
    public XsOrderQn selectXsOrderQnById(Long id)
    {
        return xsOrderQnMapper.selectXsOrderQnById(id);
    }

    /**
     * 查询千牛订单列表
     * 
     * @param xsOrderQn 千牛订单
     * @return 千牛订单
     */
    @Override
    public List<XsOrderQn> selectXsOrderQnList(XsOrderQn xsOrderQn)
    {
        return xsOrderQnMapper.selectXsOrderQnList(xsOrderQn);
    }

    /**
     * 新增千牛订单
     * 
     * @param xsOrderQn 千牛订单
     * @return 结果
     */
    @Override
    public int insertXsOrderQn(XsOrderQn xsOrderQn)
    {
        return xsOrderQnMapper.insertXsOrderQn(xsOrderQn);
    }

    /**
     * 修改千牛订单
     * 
     * @param xsOrderQn 千牛订单
     * @return 结果
     */
    @Override
    public int updateXsOrderQn(XsOrderQn xsOrderQn)
    {
        return xsOrderQnMapper.updateXsOrderQn(xsOrderQn);
    }

    /**
     * 批量删除千牛订单
     * 
     * @param ids 需要删除的千牛订单主键
     * @return 结果
     */
    @Override
    public int deleteXsOrderQnByIds(Long[] ids)
    {
        return xsOrderQnMapper.deleteXsOrderQnByIds(ids);
    }

    /**
     * 删除千牛订单信息
     * 
     * @param id 千牛订单主键
     * @return 结果
     */
    @Override
    public int deleteXsOrderQnById(Long id)
    {
        return xsOrderQnMapper.deleteXsOrderQnById(id);
    }


    @Override
    public void importQNOrder(MultipartFile file) {
        ExcelUtil<XsOrderQnImportDto> util = new ExcelUtil<XsOrderQnImportDto>(XsOrderQnImportDto.class);
        if (file.isEmpty()) {
            throw new GlobalException("上传的文件为空");
        }
        int count = 2;

        String orderId = null;
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream); // 支持.xlsx格式的Excel文件
            // 表存在数据
            List<XsOrderQn> exist = new ArrayList<>();
            // 表不存在数据
            List<XsOrderQn> nonentity = new ArrayList<>();
            // 查询全部订单
            List<XsOrderQn> orderQnList = this.lambdaQuery().list();

            Map<String, String> map = new HashMap<>();
            xsStoreService.lambdaQuery().list().forEach(store -> {
                map.put(store.getStoreName(), store.getStoreCode());
            });

            // 遍历每个工作表
            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                String sheetName = workbook.getSheetAt(sheetIndex).getSheetName();
                // 数据列表
                List<XsOrderQnImportDto> importDtoList = util.importExcel(sheetName, file.getInputStream(), 0);

                if (StringUtils.isNotEmpty(importDtoList)) {
                    for (XsOrderQnImportDto importDto : importDtoList) {

//                        if (StringUtils.isNotEmpty(importDto.getOrderStatus())) {
//                            Pattern pattern = Pattern.compile("关|闭");
//                            Matcher matcher = pattern.matcher(importDto.getOrderStatus());
//                            if (matcher.find()) {
//                                continue; // 跳过当前行
//                            }
//                        }

                        orderId = importDto.getAcookieId();
                        XsOrderQn orderQn = new XsOrderQn();

                        BeanUtil.copyProperties(importDto, orderQn);
                        orderQn.setUpdateBy(SecurityUtils.getUsername());
                        orderQn.setUpdateTime(DateUtils.getNowDate());
                        // 订单状态
                        if (StringUtils.isNotEmpty(importDto.getOrderStatus())) {
                            orderQn.setOrderStatus("交易成功".equals(importDto.getOrderStatus()) ? "2" :
                                    "买家已付款，等待卖家发货".equals(importDto.getOrderStatus()) ? "3" :
                                            "卖家已发货，等待买家确认".equals(importDto.getOrderStatus()) ? "4" : "1");
                        }
                        if (StringUtils.isNotEmpty(map)) {
                            Pattern pattern = Pattern.compile("笔|墨");
                            Matcher matcher = pattern.matcher(importDto.getStoreName());
                            if (matcher.find()) {
                                orderQn.setStoreCode(map.get("笔墨画千秋"));
                                orderQn.setOrderId(OrderNumberGenerator.generateOrderNumber("BM"));
                            } else {
                                orderQn.setStoreCode(map.get("回字格"));
                                orderQn.setOrderId(OrderNumberGenerator.generateOrderNumber("HZG"));
                            }
                        }
                        // 订单来源
                        orderQn.setOrderSource("千牛");

                        if (StringUtils.isNotEmpty(orderQnList)) {
                            Set<String> orderIdList = orderQnList.stream().map(XsOrderQn::getAcookieId)
                                    .filter(id -> id != null && !id.isEmpty())
                                    .collect(Collectors.toSet());

                            if (orderIdList.contains(orderQn.getAcookieId())) {
                                orderQnList.stream()
                                        .filter(o -> Objects.equals(o.getAcookieId(), importDto.getAcookieId()))
                                        .findFirst().ifPresent(existingOrder -> {
                                            orderQn.setId(existingOrder.getId());
                                            orderQn.setOrderId(existingOrder.getOrderId());
                                            orderQn.setUpdateBy(SecurityUtils.getUsername());
                                            orderQn.setUpdateTime(DateUtils.getNowDate());
                                            exist.add(orderQn);
                                        });
                            } else {
                                orderQn.setCreateBy(SecurityUtils.getUserId().toString());
                                orderQn.setCreateTime(DateUtils.getNowDate());
                                nonentity.add(orderQn);
                            }
                        } else {
                            orderQn.setCreateBy(SecurityUtils.getUserId().toString());
                            orderQn.setCreateTime(DateUtils.getNowDate());
                            nonentity.add(orderQn);
                        }
                        count++;
                    }
                } else {
                    throw new GlobalException("导入失败！excel第" + sheetIndex + 1 + "个工作表内数据为空");
                }
            }
            taskExecutor.submit(() -> {
                try {
                    if (StringUtils.isNotEmpty(exist)) {
                        this.updateBatchById(exist);
                    }
                    if (StringUtils.isNotEmpty(nonentity)) {
                        this.saveBatch(nonentity);
                    }
                } catch (Exception e) {
                    System.out.println("失败！" + e);
                }finally {
                    System.out.println("结束");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("文件读取错误");
        } catch (Exception e) {
            throw new RuntimeException(e + "--" + count + "---" + orderId);
        }

    }
}
